package com.xsystem.api.publicapi.auth;

import java.util.HashMap;
import java.util.Map;

import com.xsystem.api.Api;
import com.xsystem.api.AuthenticatedApi;
import com.xsystem.api.exception.RequiredParamsMissingException;
import com.xsystem.api.util.MessagesUtil;
import com.xsystem.user.UserEngine;
import com.xsystem.user.exception.UserNotFoundException;
import com.xsystem.user.exception.UserUnauthorizedException;

public class Login extends Api {

	public static final String SUCCESS_MSG = "successLogin";
	private UserEngine userEngine;

	@Override
	public Map<String, Object> executeApi(Map<String, String> parameters)
			throws RequiredParamsMissingException {

		String username = parameters.get(Api.IN_USERNAME);
		String password = parameters.get(Api.IN_PASSWORD);

		if (username == null) {
			return prepareCustomErrorResponse(
					AuthenticatedApi.ERROR_ACCOUNT_NOT_FOUND,
					MessagesUtil.getProperty(AuthenticatedApi.class,
							AuthenticatedApi.ERROR_ACCOUNT_NOT_FOUND, null));
		}
		if (password == null) {
			return prepareCustomErrorResponse(
					AuthenticatedApi.ERROR_USER_UNAUTHORIZED,
					MessagesUtil.getProperty(AuthenticatedApi.class,
							AuthenticatedApi.ERROR_USER_UNAUTHORIZED, null));
		}

		try {
			userEngine.getAuthenticatedUser(username, password);
		} catch (UserNotFoundException e) {
			return prepareCustomErrorResponse(
					AuthenticatedApi.ERROR_ACCOUNT_NOT_FOUND,
					MessagesUtil.getProperty(AuthenticatedApi.class,
							AuthenticatedApi.ERROR_ACCOUNT_NOT_FOUND, null));
		} catch (UserUnauthorizedException e) {
			return prepareCustomErrorResponse(
					AuthenticatedApi.ERROR_USER_UNAUTHORIZED,
					MessagesUtil.getProperty(AuthenticatedApi.class,
							AuthenticatedApi.ERROR_USER_UNAUTHORIZED, null));
		}

		HashMap<String, Object> hm = new HashMap<String, Object>();

		return prepareSuccessResponse(hm, getProperty(SUCCESS_MSG, "success"));

	}

	public UserEngine getUserEngine() {
		return userEngine;
	}

	public void setUserEngine(UserEngine userEngine) {
		this.userEngine = userEngine;
	}

}
